package com.Junit.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

public class RedisUtil {
    public static Jedis getInstance() {
        return RedisUtilHolder.jedis;
    }

    public static boolean setNx(String key, String value) {
//        if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {
//            return false;
//        }
        try {
            boolean res = 1 == getInstance().setnx(key,
                    value);
//            if (res && expireSeconds > 0) {
            getInstance().expire(key, 3000);
//            }
            return res;
        } catch (Throwable e) {
//            log.error(String.format("****setnx异常,key:%s,value:%s****", key, value), e);
            return false;
        }
    }


    public static boolean casSetValue(String key, String value) {
        getInstance().watch(key);
        Transaction tx = getInstance().multi();
        tx.set(key,value);
        tx.expire(key,3000);
        List<Object> results = tx.exec();
        if(results.size()<=0){
            return false;
        }else{
            return true;
        }
    }

    public static String get(String key) {
       return getInstance().get(key);
    }



    public static long getRedisServiceTime() {
        Jedis jedisReadPool = null;
        try {
            List<String> timeList = getInstance().time();
//            redisService.returnJedisByKey(getReadRedisFlag(),jedisReadPool);
            long unixSeconds = Long.parseLong(timeList.get(0));
            long microseconds = Long.parseLong(timeList.get(1));
            //将微秒转为毫秒
            return unixSeconds * 1000 + microseconds / 1000;
        } catch (Throwable e) {
//            log.error("****getRedisServiceTime异常****", e);
//            if(jedisReadPool !=null){
//                try{
//                    redisService.returnJedisByKey(getReadRedisFlag(),jedisReadPool);
//                }catch (Exception e){
//                    log.error(String.format("****尝试回收redispool资源异常****"), e);
//                }
//            }
            return 0;
        } finally {
            if (jedisReadPool != null) {
                jedisReadPool.close();
            }
        }
    }

    public static void delKey(String key){
        getInstance().del(key);
    }

    private static class RedisUtilHolder {
        public static final Jedis jedis = new Jedis("127.0.0.1", 6379);
    }
}
